from Crypto.Cipher import AES
import base64
import os
import gdata.docs.service
import sys
import rsa

BLOCK_SIZE = 32
PADDING = '{'



def aes_encrypt( secret, content) :
	# one-liner to sufficiently pad the text to be encrypted
	pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

	# one-liners to encrypt/encode and decrypt/decode a string
	# encrypt with AES, encode with base64
	EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
	
	# create a cipher object using the random secret
	cipher = AES.new(secret)
	
	# encode a string
	return EncodeAES(cipher, content)



#Get the original file
print 'File path:'
path = sys.stdin.readline().rstrip()
orig_file = open(path)
file_content = orig_file.read()
orig_file.close()

#create random AES key
encr_key = os.urandom(BLOCK_SIZE)

#encrypt content
ct = aes_encrypt(encr_key, file_content)

#encrypt key with the owner's public key
home = os.getenv("HOME")
f = open(home + '/.gd_pub', 'r')
pub = eval(f.read())

encrypted_key = rsa.encrypt(encr_key, pub)




#write to temp file
temp_path = path + '_work.txt'
work_file = open(temp_path,'w')
work_file.write('EncryptedKeys:START\n')
work_file.write('Key:' + encrypted_key + ', pub : ' + str(pub) + '\n')
work_file.write('EncryptedKeys:END\n')
work_file.write('Content:START\n')
work_file.write(ct + '\n')
work_file.write('Content:END\n')
work_file.close()

# Create a client class which will make HTTP requests with Google Docs server.
client = gdata.docs.service.DocsService()
# Authenticate using your Google Docs email address and password.
print 'User name :'
user_name = sys.stdin.readline().rstrip()
print 'Password :'
password = sys.stdin.readline().rstrip()

client.ClientLogin(user_name, password)

ms = gdata.MediaSource(file_path=temp_path, content_type=gdata.docs.service.SUPPORTED_FILETYPES['TXT'])

print 'Document title :'
title = sys.stdin.readline().rstrip()

entry = client.Upload(ms, title)
print 'Document now accessible online at:', entry.GetAlternateLink().href




